package lab.netflix.eureka;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceCanceledEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class EurekaInstanceCanceledListener implements ApplicationListener<EurekaInstanceCanceledEvent> {

	@Autowired
	EurekaClient eurekaClient;

	@Autowired
	PeerAwareInstanceRegistry registry;

	@Override
	public void onApplicationEvent(EurekaInstanceCanceledEvent event) {
		System.out.println("************** EurekaInstanceCanceledListener.onApplicationEvent()... **************");

		// 可以把这个 serviceId 发给各个客户端, 把它从客户端的本地缓存中删除
		String cancelledServerId = event.getServerId();

//		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse httpResponse = null;

		Applications applications = registry.getApplications();
		try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
			for (Application application : applications.getRegisteredApplications()) {
				for (InstanceInfo instance : application.getInstances()) {
					String ipAddr = instance.getIPAddr();
					int port = instance.getPort();
					HttpGet httpGet = new HttpGet(String.join("", "http://", ipAddr, ":", String.valueOf(port), "/apps/refresh"));
					httpResponse = httpClient.execute(httpGet);
					HttpEntity httpEntity = httpResponse.getEntity();
					System.out.println(EntityUtils.toString(httpEntity));
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (httpResponse != null) {
				try {
					httpResponse.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
